package com.ruoyi.project.system.controller;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SysProfession;
import com.ruoyi.project.system.service.ISysProfessionService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * 工种信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/profession")
public class SysProfessionController extends BaseController
{
    @Autowired
    private ISysProfessionService professionService;

    /**
     * 获取工种列表
     */
    @PreAuthorize("@ss.hasPermi('system:profession:list')")
    @GetMapping("/list")
    public AjaxResult list(SysProfession Profession)
    {
        List<SysProfession> Professions = professionService.selectProfessionList(Profession);
        return AjaxResult.success(Professions);
    }

    /**
     * 查询工种列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:profession:list')")
    @GetMapping("/list/exclude/{id}")
    public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id)
    {
        List<SysProfession> Professions = professionService.selectProfessionList(new SysProfession());
        Iterator<SysProfession> it = Professions.iterator();
        while (it.hasNext())
        {
            SysProfession d = (SysProfession) it.next();
            if (d.getId().intValue() == id
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), id + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(Professions);
    }

    /**
     * 根据工种编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:profession:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return AjaxResult.success(professionService.selectProfessionById(id));
    }

    /**
     * 获取工种下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysProfession Profession)
    {
        List<SysProfession> Professions = professionService.selectProfessionList(Profession);
        return AjaxResult.success(professionService.buildProfessionTreeSelect(Professions));
    }

    /**
     * 加载对应角色工种列表树
     */
    @GetMapping(value = "/roleProfessionTreeselect/{roleId}")
    public AjaxResult roleProfessionTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysProfession> Professions = professionService.selectProfessionList(new SysProfession());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", professionService.selectProfessionListByRoleId(roleId));
        ajax.put("Professions", professionService.buildProfessionTreeSelect(Professions));
        return ajax;
    }

    /**
     * 新增工种
     */
    @PreAuthorize("@ss.hasPermi('system:profession:add')")
    @Log(title = "工种管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysProfession Profession)
    {
        if (UserConstants.NOT_UNIQUE.equals(professionService.checkProfessionNameUnique(Profession)))
        {
            return AjaxResult.error("新增工种'" + Profession.getName() + "'失败，工种名称已存在");
        }
        Profession.setCreateBy(SecurityUtils.getUsername());
        return toAjax(professionService.insertProfession(Profession));
    }

    /**
     * 修改工种
     */
    @PreAuthorize("@ss.hasPermi('system:profession:edit')")
    @Log(title = "工种管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysProfession Profession)
    {
        if (UserConstants.NOT_UNIQUE.equals(professionService.checkProfessionNameUnique(Profession)))
        {
            return AjaxResult.error("修改工种'" + Profession.getName() + "'失败，工种名称已存在");
        }
        else if (Profession.getParentId().equals(Profession.getId()))
        {
            return AjaxResult.error("修改工种'" + Profession.getName() + "'失败，上级工种不能是自己");
        }
        else if (StringUtils.equals(UserConstants.PROFESSION_DISABLE, Profession.getStatus())
                && professionService.selectNormalChildrenProfessionById(Profession.getId()) > 0)
        {
            return AjaxResult.error("该工种包含未停用的子工种！");
        }
        Profession.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(professionService.updateProfession(Profession));
    }

    /**
     * 删除工种
     */
    @PreAuthorize("@ss.hasPermi('system:profession:remove')")
    @Log(title = "工种管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        if (professionService.hasChildByProfessionId(id))
        {
            return AjaxResult.error("存在下级工种,不允许删除");
        }
        if (professionService.checkProfessionExistUser(id))
        {
            return AjaxResult.error("工种存在用户,不允许删除");
        }
        return toAjax(professionService.deleteProfessionById(id));
    }
}
